<?php

use Hyperf\Utils\ApplicationContext;
use Hyperf\DB\DB;

/**---------------------------------------------
 *  获得工厂类函数
 * ---------------------------------------------
 */
//获取redis
function redis(){
    $container = ApplicationContext::getContainer();
    return $container->get(\Hyperf\Redis\Redis::class);
}
//缓存快捷方法
function cache($key, $value='', $expire=null){
    $container = ApplicationContext::getContainer();
    $redis = $container->get(\Hyperf\Redis\Redis::class);
    if(empty($value)) return $redis->get($key);
    return $redis->setx($key, $value, $expire);
}
//获取mysql
function table($table){
    return Db::table($table);
}



/**---------------------------------------------
 *  数据库快捷操作函数
 * ---------------------------------------------
 */

//获取单个字段信息
function db_get_field($table, $where, $field='id') : string
{
    $sql = "SELECT {$field} FROM {$table} WHERE {$where} LIMIT 1";
    $res = DB::query( str_replace('##_', '', $sql) ); 
    return $res[0][$field] ?? '';
}
//获取单行记录
function db_get_row($table, $where) : array
{
    $sql = "SELECT * FROM {$table} WHERE {$where} LIMIT 1";
    $res = DB::query( str_replace('##_', '', $sql) ); 
    return $res[0] ?? [];
}
//获取多行记录
function db_get_all($table, $where) : array
{
    $sql = "SELECT * FROM {$table} WHERE {$where}";
    $res = DB::query( str_replace('##_', '', $sql) ); 
    return $res ?? [];
}
//执行sql语句
function db_query($sql) : array
{
    $res = DB::query( str_replace('##_', '', $sql) ); 
    return $res ?? [];
}
//生成where in条件
function db_where_in($field, $items)
{
    if(is_array($items)){
        $where_str = !empty($items) ? "'".join("','", array_values($items) )."'" : "''"; 
        return $field." IN({$where_str}) ";
    }
    $where_str = !empty($items) ? $items : "''";
    return $field." IN({$where_str}) ";
}

//插入单行记录
function db_insert($table, $data) : int
{
    $sql = '';
    foreach( $data as $k=>$v ) $sql .= " `{$k}` = '" . $v . "',";
    $sql = rtrim($sql, ',');
    $res = DB::execute( str_replace('##_', '', "INSERT INTO {$table} {$sql}") ); 
    return $res;
}
//插入多行记录
// function db_add_all($table, $data){
//     return db($table)->data($data)->insertAll();
// }

//更新单行记录
function db_update($table, $data, $where)
{
    $sql = '';
    foreach( $data as $key=>$val ) $sql .= " `{$key}` = '" . $val . "',";
    $sql = "UPDATE {$table} SET " . rtrim($sql, ',') . " WHERE {$where}";
    $res = DB::execute( str_replace('##_', '', $sql) ); 
    return $res;
}
//字段增加
function db_field_inc($table, $where, $field='', $num=1){
    $num = $num >= 0 ? "+{$num}" : "{$num}";
    // db($table)->where($where)->setInc($field, $num);
    $sql = "UPDATE {$table} SET {$field}=`{$field}`{$num} WHERE {$where}";
    $res = DB::execute( str_replace('##_', '', $sql) ); 
    return $res;
}

//插入记录,存在则替换
//demo: db_replace_all('fa_ttt', ['admin_id'=>1, 'cat_id'=>1], ['updatetime'=>time()]);
function db_replace_row($table, $insert_data, $update_data){
    if(!is_array($insert_data) || count($insert_data)<=0) return false;
    $field_str = $value_str = $update_field_str = [];
    foreach($insert_data as $k=>$v){
        $field_str[] = $k;
        $value_str[] = "'$v'";
    }
    $field_str = implode(',', $field_str);
    $value_str = implode(',', $value_str);
    foreach($update_data as $k=>$v){
        $update_field_str[] = "$k='{$v}'";
    }
    $update_field_str = implode(',', $update_field_str);
    $sql = "INSERT INTO {$table}({$field_str})"." VALUE({$value_str}) "." ON DUPLICATE KEY UPDATE {$update_field_str}";
    return DB::execute($sql);
}
//插入多行记录,存在则替换
//demo: db_replace_all('fa_ttt',[['admin_id'=>1, 'cat_id'=>1],['admin_id'=>2, 'cat_id'=>2],], ['updatetime']);
function db_replace_all($table, $insert_data, $update_data){
    if(!is_array($insert_data) || count($insert_data)<=0) return false;
    $field_str = $value_str = $update_field_str = '';
    foreach($insert_data as $k=>$v){
        $field_str = implode(',',  array_keys($v) );
        $value_str .= "(".implode(',',  array_values($v) )."),";
    }
    $value_str = rtrim($value_str, ',');
    foreach($update_data as $kk=>$vv){
      $update_field_str .= "$vv=values($vv),";
    }
    $update_field_str = rtrim($update_field_str, ',');
    $sql = "INSERT INTO {$table}({$field_str})"." VALUES {$value_str} "." ON DUPLICATE KEY UPDATE {$update_field_str}";
    return DB::execute($sql);
}
//插入记录,存在则不插入
//demo: db_replace_all('fa_ttt', ['admin_id'=>1, 'cat_id'=>1], ['updatetime'=>time()]);
function db_insert_or($table, $insert_data, $update_data){
    if(!is_array($insert_data) || count($insert_data)<=0) return false;
    $field_str = $value_str = $update_field_str = $update_value_str = [];
    foreach($insert_data as $k=>$v){
        $field_str[] = $k;
        $value_str[] = "'$v'";
    }
    $field_str = implode(',', $field_str);
    $value_str = implode(',', $value_str);
    foreach($update_data as $k=>$v){
        $update_field_str[] = "$k";
        $update_value_str[] = " AND $k='{$v}' ";
    }
    $update_field_str = implode(',', $update_field_str);
    $update_value_str = implode('', $update_value_str);
    $sql = "INSERT INTO {$table}($field_str) SELECT {$value_str} FROM DUAL ".
           "WHERE NOT EXISTS(SELECT {$update_field_str} FROM {$table} WHERE 1 {$update_value_str})";
    return DB::execute($sql);
}
//------ end ---------------- //




/**
 * 二维数组操作快捷方法 --- start --- //
 */
function arrAll($arr, $key, $val){
    $res = [];
    foreach ($arr as $k => $v) {
        if($v[$key] == $val) $res[] = $v;
    }
    return $res;
}
function arrRow($arr, $key, $val){
    $res = [];
    foreach ($arr as $k => $v) {
        if($v[$key] == $val) return $v;
    }
    return $res;
}
function arrField($arr, $key, $val, $field=''){
    foreach ($arr as $k => $v) {
        if( $v[$key] == $val && isset($v[$field]) ) return $v[$field];
    }
    return '';
}
//------ end ------ //

